Enumerations
- An enumeration defines a common type for a group of related values
- The value for each case is optional, the value can be a string, a character, or a value of any integer or floating-point type.Unlike C and Objective-C, Swift enumeration cases are not assigned a default integer value when they are created.
- cases can specify associated values of any type to be stored along with each different case value
Enumeration Syntax
Each enumeration definition defines a brand new type, which name should be with capital and singular rather than plural.
1 | enum SomeEnumeration { |
Matching Enumeration Values with a Switch Statement
1 | directionToHead = .south |
Associated Values
- store additional custom information
- store associated values of any given type, and the value types can be different for each case of the enumeration if needed
- Extract value from associated value by prefix
let
orvar
1 | enum Barcode { |
Raw Value vs. Associate Value
Item | Raw value | Associate value |
---|---|---|
When to set value | first define the enumeration | set when you create a new instance |
value | each case is always the same | can be different between each case |
value type | string,character,integer,float | any given type |
Raw Values
- default values (called raw values), which are all of the same type.
- Raw values can be strings, characters, or any of the integer or floating-point number types. Each raw value must be unique within its enumeration declaration.
1 | // stores raw ASCII values alongside named enumeration cases: |
Implicitly Assigned Raw Values
- if type is
Int
,default value is 0, then increment. - if type is
String
,the implicit value for each case is the text of that case’s name.
1 | enum Planet: Int { |
Initializing from a Raw Value
1 | let possiblePlanet = Planet(rawValue: 7) |
Recursive Enumerations
????
1 | enum ArithmeticExpression { |